﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		SecurityProviderHelper.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 // 
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;
using Dexter.Domain.Model;

namespace Dexter.Web.Security {
	internal static class SecurityProviderHelper {
		public static byte[] HexToByte ( string hexString ) {
			var buffer = new byte[( hexString.Length / 2 ) + 1];
			for ( int i = 0; i <= ( ( hexString.Length / 2 ) - 1 ); i++ ) {
				buffer[ i ] = Convert.ToByte ( hexString.Substring ( i * 2 , 2 ) , 0x10 );
			}
			return buffer;
		}

		public static string CreateKey ( int numBytes ) {
			var provider = new RNGCryptoServiceProvider ( );
			var data = new byte[numBytes];
			provider.GetBytes ( data );
			return BytesToHexString ( data );
		}

		public static string BytesToHexString ( byte[] bytes ) {
			var builder = new StringBuilder ( 0x40 );

			foreach ( byte t in bytes ) {
				builder.Append ( string.Format ( "{0:X2}" , t ) );
			}

			return builder.ToString ( );
		}

		public static User FromMembershipUser ( MembershipUser mu , User user ) {
			user.Email = mu.Email;
			user.Comments = mu.Comment;

			if ( mu.IsApproved != user.IsApproved ) {
				if ( mu.IsApproved ) {
					user.Approve ( );
				}
				else {
					user.Unapprove ( );
				}
			}

			if ( mu.IsLockedOut != user.IsLockedOut ) {
				if ( mu.IsLockedOut ) {
					user.Lock ( );
				}
				else {
					user.Unlock ( );
				}
			}

			user.UpdateLastActivityDate ( );

			return user;
		}

		public static MembershipUser ToMembershipUser ( string providerName , User user ) {
			return new MembershipUser ( providerName , user.Username , user.Id , user.Email , user.PasswordQuestion , user.Comments , user.IsApproved , user.IsLockedOut , user.CreationDate , user.LastLoginDate , user.LastActivityDate , user.LastPasswordChangeDate , user.LastLockedOutDate);
		}
	}
}
